package com.jiaeda.shiroweb.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * Created by chengchaopeng on 2018/5/29.
 */
@Controller
public class UserController {
    @RequestMapping(value = "/subLogin", method = RequestMethod.POST)
    public String subLogin(@RequestParam("userName") String userName,
                           @RequestParam("password") String password) {

        UsernamePasswordToken token = new
                UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //角色判断
            subject.checkRole("user");
            //权限判断
            subject.checkPermission("user_model");
        } catch (AuthenticationException e) {
            return e.getMessage();
        }
        return "index";
    }

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String index() {
        return "login";
    }
    //错误页面展示
    @RequestMapping(value = "/error",method = RequestMethod.POST)
    public String error(){
        return "error ok!";
    }



    /**
     * 测试角色
     *
     * @return
     */

    @RequiresRoles(value = {"user"}, logical = Logical.OR)
    @RequestMapping(value = "/testRole", method = RequestMethod.GET)
    @ResponseBody
    public String testRole() {
            return "testRole success";
    }

    @RequiresRoles(value = {"user1"}, logical = Logical.OR)
    @RequestMapping(value = "/testRole1", method = RequestMethod.GET)
    @ResponseBody
    public String testRole1() {
            return "testRole1 success";
    }

    /**
     * 测试权限
     *
     * @return
     */
    @RequiresPermissions("user_model")
    @RequestMapping(value = "/testPermission", method = RequestMethod.GET)
    @ResponseBody
    public String testPermission() {
        return "testPermission success";
    }

    @RequiresPermissions("user_model1")
    @RequestMapping(value = "/testPermission1", method = RequestMethod.GET)
    @ResponseBody
    public String testPermission1() {
        return "testPermission1 success";
    }
}
